package com.itheima.web.controller.cargo;

import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import com.itheima.common.utils.UtilFuns;
import com.itheima.domain.cargo.ContractProduct;
import com.itheima.domain.cargo.ContractProductExample;
import com.itheima.domain.cargo.Factory;
import com.itheima.domain.cargo.FactoryExample;
import com.itheima.service.cargo.ContractProductService;
import com.itheima.service.cargo.FactoryService;
import com.itheima.web.controller.BaseController;
import com.itheima.web.utils.FileUploadUtil;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/cargo/contractProduct")
public class ContractProductController extends BaseController {

    @Reference
    private ContractProductService contractProductService;

    @Reference
    private FactoryService factoryService;

    @Autowired
    private FileUploadUtil fileUploadUtil;


    @RequestMapping(value = "/import",name = "导出货物excel列表")
    public String importExcel(String contractId,MultipartFile file) throws IOException {

        //定义list集合将cell的值保存contractProduct对象中
        List<ContractProduct> contractProducts = new ArrayList<>();
        //读取excel信息
        Workbook workbook = new XSSFWorkbook(file.getInputStream());//得到workbook
        Sheet sheet = workbook.getSheetAt(0);//得到sheet
        //循环遍历row，将excel中的每一行数据包装成一个contractProduct对象
        for (int i = 1; i <= sheet.getLastRowNum(); i++) {//循环行
            Row row = sheet.getRow(i);

            Object[] objs = new Object[10];//数组装入一行的数据
            for (int j = 0; j < row.getLastCellNum(); j++) {
                Cell cell = row.getCell(j);
                if(cell != null){
                    Object obj = getCellValue(cell);//得到cell的值
                    objs[j] = obj;//将值保存到数组中
                }
            }
            //将row中每一个cell的值都封装到了contractProduct对象中
            ContractProduct contractProduct = new ContractProduct(objs, getCurrentUserCompanyId(), getCurrenUserCompanyName());
            //将合同id封装到contractProduct对象中
            contractProduct.setContractId(contractId);
            //添加到集合
            contractProducts.add(contractProduct);
        }
        //存入数据库
        contractProductService.saveAll(contractProducts);
        //返回
        return "redirect:/cargo/contractProduct/list.do?contractId="+contractId;
    }

    //获取不同的类型值
    private Object getCellValue(Cell cell) {
        Object object = null;
        CellType cellType = cell.getCellType();
        switch (cellType){
            case STRING:
                object = cell.getStringCellValue();
                break;
            case BOOLEAN:
                object = cell.getBooleanCellValue();
                break;
            case NUMERIC:
                if(DateUtil.isCellDateFormatted(cell)){
                    object = cell.getDateCellValue();
                }else {
                    object = cell.getNumericCellValue();
                }
                break;

        }
        return object;
    }

    @RequestMapping(value = "/toImport",name = "前往批量上传货物")
    public String toImport(String contractId){
        request.setAttribute("contractId",contractId);
        return "cargo/product/product-import";
    }

    @RequestMapping(value = "/list",name = "查询合同下货物的列表")
    public String list(String contractId,@RequestParam(defaultValue = "1") int page,@RequestParam(defaultValue = "5") int size){

        //1.创建查询条件
        ContractProductExample contractProductExample = new ContractProductExample();
        //2.设置查询条件，合同的id等于方法的形参contractId
        contractProductExample.createCriteria().andContractIdEqualTo(contractId);
        //3.使用条件查询
        PageInfo pageInfo = contractProductService.findAll(contractProductExample, page, size);
        //4.存入请求域中
        request.setAttribute("page",pageInfo);
        //5.设置合同的id存入请求域
        request.setAttribute("contractId",contractId);
        //6.创建factory的特例（查询条件）
        FactoryExample factoryExample = new FactoryExample();
        //7.设置查询条件
        factoryExample.createCriteria().andCtypeEqualTo("货物");
        //8.查询生产厂家
        List<Factory> factoryList = factoryService.findAll(factoryExample);
        //9.把厂家列表存入请求域中
        request.setAttribute("factoryList",factoryList);
        //10.返回
        return "cargo/product/product-list";
    }

    @RequestMapping(value = "/edit",name = "更新获取保存货物")                                        //productPhoto
    public String edit(ContractProduct contractProduct, MultipartFile productPhoto)throws Exception{
        if(UtilFuns.isEmpty(contractProduct.getId())){
            //保存
            contractProduct.setCompanyId(super.getCurrentUserCompanyId());
            contractProduct.setCompanyName(super.getCurrenUserCompanyName());
            String imgPath = "";
            //判断文件字段是否有值
            /*if(productPhoto!=null){
                //文件上传
                imgPath = "http://"+fileUploadUtil.upload(productPhoto);
            }
            contractProduct.setProductImage(imgPath);*/
            contractProductService.save(contractProduct);
        }else {//更新
            contractProductService.update(contractProduct);
        }
        return "redirect:/cargo/contractProduct/list.do?contractId="+contractProduct.getContractId();
    }

    @RequestMapping(value = "/toUpdate",name = "前往货物编辑页面")
    public String toUpdate(String id){
        //数据回显
        ContractProduct contractProduct = contractProductService.findById(id);
        request.setAttribute("contractProduct",contractProduct);
        //创建factory的特例
        FactoryExample factoryExample = new FactoryExample();
        //设置查询条件
        factoryExample.createCriteria().andCtypeEqualTo("货物");
        //查询生成厂家
        List<Factory> factoryList = factoryService.findAll(factoryExample);
        //存入请求域
        request.setAttribute("factoryList",factoryList);
        //返回
        return "cargo/product/product-update";
    }

    @RequestMapping(value = "/delete",name = "删除货物")
    public String delete(String id,String contractId){
        contractProductService.delete(id);
        return "redirect:/cargo/contractProduct/list.do?contractId="+contractId;
    }


}
